package com.gitee.lougnib.simplekits.common_impls.jackson;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.lougnib.simplekits.common_faces.exception.Exceptions;

public class JacksonKit {

    static ObjectMapper mapper = new ObjectMapper();

    /**
     * 将 JSON 字符串装换成列表。
     * JSON 字符串的格式：
     * [
     *  {name1:value1, name2:value2},
     *  {name1:value1, name2:value2}
     * ]
     *
     * @param data
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Map<String, String>> toMapList(String json) {
        try {
            return (List<Map<String, String>>) mapper.readValue(json, List.class);
        } catch (IOException e) {
            throw Exceptions.toRuntime(e);
        }
    }
    
    @SuppressWarnings("unchecked")
    public static Map<String, Object> toMap(String json) {
        try {
            return (Map<String, Object>) mapper.readValue(json, Map.class);
        } catch (IOException e) {
            throw Exceptions.toRuntime(e);
        }
    }

    public static <T> T toObject(String json, Class<T> type) {
        try {
            return (T) mapper.readValue(json, type);
        } catch (IOException e) {
            throw Exceptions.toRuntime(e);
        }
    }

    public static <T> T toObject(String json, TypeReference<T> valueTypeRef) {
        try {
            return mapper.readValue(json, valueTypeRef);
        } catch (IOException e) {
            throw Exceptions.toRuntime(e);
        }
    }

    public static void toJsonFile(String path, Object value) {
    	File jsonFile = new File(path);
    	if (!jsonFile.getParentFile().exists()) {
    		jsonFile.getParentFile().mkdirs();
    	}
    	try {
			mapper.writer(new DefaultPrettyPrinter()).writeValues(jsonFile).write(value);
		} catch (IOException e) {
            throw Exceptions.toRuntime(e);
		}
    }

}
